package com.youngcms.controller.admin;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.youngcms.bean.Channel;
import com.youngcms.bean.ChannelModel;
import com.youngcms.bean.Content;
import com.youngcms.bean.ContentImage;
import com.youngcms.bean.ContentOption;
import com.youngcms.bean.ContentText;
import com.youngcms.bean.ContentVideo;
import com.youngcms.bean.Model;
import com.youngcms.controller.base.AdminBaseController;
import com.youngcms.service.ChannelModelService;
import com.youngcms.service.ChannelService;
import com.youngcms.service.ContentImageService;
import com.youngcms.service.ContentOptionService;
import com.youngcms.service.ContentService;
import com.youngcms.service.ContentTextService;
import com.youngcms.service.ContentVideoService;
import com.youngcms.service.FlowFaceService;
import com.youngcms.service.ModelService;
import com.youngcms.utils.Constants;
import com.youngcms.utils.DateUtil;
import com.youngcms.utils.DictUtil;
import com.youngcms.utils.ListTypeParameter;
import com.youngcms.utils.SessionKey;
import com.youngcms.vo.ActionResult;
import com.youngcms.vo.LabelValue;
import com.youngcms.vo.QueryResult;
@Controller
@RequestMapping("/admin/content/")
@SessionAttributes("pageForm")
public class ContentController extends AdminBaseController{

     @Autowired
     private ContentService contentService;
     @Autowired
     private ChannelService channelService;
     @Autowired
     private FlowFaceService flowFaceService;
     @Autowired
     private ChannelModelService channelModelService;
     @Autowired
     private ModelService modelService;
     @Autowired
     private ContentTextService contentTextService;
     @Autowired
     private ContentImageService contentImageService;
     @Autowired
     private ContentOptionService contentOptionService;
     @Autowired
     private ContentVideoService contentVideoService;

     @RequestMapping("dataPage")
     public ModelAndView dataPage(Content content,HttpServletRequest request) throws Exception{
        ModelAndView mnv = new ModelAndView();
        
        mnv.setViewName("view/admin/content/dataPage");
        return mnv;
     }
     
     @RequestMapping("getChannelModel")
     @ResponseBody
     public Object getChannelModel(Content content,HttpServletRequest request) throws Exception{
        Map<String, Object> params=new HashMap<String, Object>();
		params.put("channelId",content.getChannelId());
		QueryResult<ChannelModel> queryResult=channelModelService.list(params);
        return queryResult.getQueryResult();
     }
     
     @RequestMapping("flowList")
     public ModelAndView flowList(Content content,HttpServletRequest request) throws Exception{
    	String whereSql=null;
    	if(StringUtils.isNotBlank(whereSql)){
    		whereSql+=" and flowFaceValue in ("+getStatus(1, flowFaceService, request)+")";
    	}else{
    		whereSql="  flowFaceValue in ("+getStatus(1, flowFaceService, request)+")";
    	}
    	QueryResult<Content> queryResult=contentService.list(content);
    	content.setPageDate(queryResult.getQueryResult());
    	content.setTotalCount(queryResult.getCount());
        ModelAndView mnv = new ModelAndView();
        mnv.addObject(DEFAULT_PAGE_VIEW,content);
        mnv.setViewName("view/admin/content/flowList");
        return mnv;
     }
     
     @RequestMapping("list")
     public ModelAndView list(Content content,HttpServletRequest request) throws Exception{
    	QueryResult<Content> queryResult=contentService.list(content);
    	content.setPageDate(queryResult.getQueryResult());
    	content.setTotalCount(queryResult.getCount());
        ModelAndView mnv = new ModelAndView();
        mnv.addObject(DEFAULT_PAGE_VIEW,content);
        mnv.setViewName("view/admin/content/list");
        return mnv;
     }
     
     @RequestMapping("delete")
     @ResponseBody
     public ActionResult delete(Content content,HttpServletRequest request) throws Exception{
        ActionResult result=new ActionResult();
       try {
	     contentService.deleteByPrimaryKey(content.getId());
	     result.setSuccess(true);
	     result.setMessage(RESULE_SUCCESS_DELETE);
		 } catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(RESULE_ERROR_DELETE);
		}
		return result;
	 }

	 @RequestMapping("showForm")
	 public ModelAndView addForm(Content content,HttpServletRequest request) throws Exception{
		ModelAndView mnv = new ModelAndView();
		if(content.getId()!=null){
			content=contentService.selectByPrimaryKey(content.getId());
		}else{
			String sysUserName=(String) request.getSession().getAttribute(SessionKey.SYS_USER_NAME);
			content.setIsTop(DictUtil.getIdByNameAndEnName("isTop","否"));
			content.setIsComment(DictUtil.getIdByNameAndEnName("isComment","是"));
			content.setWeight(10);
			content.setCreateUser(sysUserName);
			content.setCreateTime(DateUtil.dateToStr(new Date(), 12));
		}
		Channel channel=channelService.selectByPrimaryKey(content.getChannelId());
		Model model=modelService.selectByPrimaryKey(content.getModelId());
		String contentText="";
		String vedioUrl="";
		List<ContentImage> contentImages=new ArrayList<ContentImage>();
		List<ContentOption> contentOptions=new ArrayList<ContentOption>();
		if(content.getId()!=null){
			Map<String, Object> params=new HashMap<String, Object>();
			params.put("contentId", content.getId());
			if(model.getHasContent()==DictUtil.getIdByNameAndEnName("hasContent", "是")){
			   QueryResult<ContentText> queryResult=contentTextService.list(params);
			   if(queryResult.getCount()>0){
				   contentText=queryResult.getQueryResult().get(0).getText();
				}
			}
			if(model.getHasGroupImages()==DictUtil.getIdByNameAndEnName("hasGroupImages", "是")){
				QueryResult<ContentImage> queryResult=contentImageService.list(params);
				contentImages=queryResult.getQueryResult();
			}
			if(model.getHasVedio()==DictUtil.getIdByNameAndEnName("hasVedio", "是")){
				QueryResult<ContentVideo> queryResult=contentVideoService.list(params);
				if(queryResult.getCount()>0){
					vedioUrl=queryResult.getQueryResult().get(0).getVideoUrl();
				}
			}
			if(model.getHasOptions()==DictUtil.getIdByNameAndEnName("hasOptions", "是")){
				QueryResult<ContentOption> queryResult=contentOptionService.list(params);
				contentOptions=queryResult.getQueryResult();
			}
		}
		mnv.addObject(DEFAULT_PAGE_FORM, content);
		mnv.addObject("channel", channel);
		mnv.addObject("model", model);
		mnv.addObject("IS_TOP_TYPE_LIST", ListTypeParameter.isTopTypeList);
	    mnv.addObject("IS_COMMENT_TYPE_LIST", ListTypeParameter.isCommentTypeList);
	    mnv.addObject("hasGroupImages", DictUtil.getIdByNameAndEnName("hasGroupImages", "是"));
	    mnv.addObject("hasVedio", DictUtil.getIdByNameAndEnName("hasVedio", "是"));
	    mnv.addObject("hasContent", DictUtil.getIdByNameAndEnName("hasContent", "是"));
	    mnv.addObject("hasOptions", DictUtil.getIdByNameAndEnName("hasOptions", "是"));
	    mnv.addObject("contentText",contentText);
	    mnv.addObject("vedioUrl", vedioUrl);
	    mnv.addObject("contentImages", contentImages);
	    mnv.addObject("contentOptions",contentOptions);
	    mnv.addObject("templates", getTemplate());
		mnv.setViewName("view/admin/content/form");
		return mnv;
	 }

	@RequestMapping("addOrUpdate")
	@ResponseBody
	public ActionResult add(Content content,HttpServletRequest request) throws Exception{
		ActionResult result=new ActionResult();
		try {
			content.setCreateTime(DateUtil.dateToStr(new Date(), 12));
			contentService.saveOrUpdate(content,request);
			result.setSuccess(true);
			result.setMessage(RESULE_SUCCESS);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(RESULE_ERROR);
		}
		return result;
	}
	
	
	private List<LabelValue> getTemplate(){
		String templatePath=context.getRealPath("/template/"+Constants.TEMPLATE_FOLDER+"/content/");
		List<LabelValue> list=new ArrayList<LabelValue>();
		File file=new File(templatePath);
		String[] templates=file.list();
		for(int i=0;i<templates.length;i++){
			LabelValue labelValue=new LabelValue();
			labelValue.setLabel(Constants.TEMPLATE_FOLDER+"/content/"+templates[i]);
			labelValue.setValue(Constants.TEMPLATE_FOLDER+"/content/"+templates[i]);
			list.add(labelValue);
		}
		return list;
	}

 
}
